App.controller('userController', ['$rootScope', '$scope', '$state', 'Page', function($rootScope, $scope, $state, Page) {

	Page.ajaxPost("department/tree.do", null, function (response) {
		$scope.depts = response.data;
	});
	// 部门树点击事件
	$scope.selectDept = function(dept) {
		$scope.dept = dept;
		$scope.userGrid.query({deptId: dept.deptId});
	}

	// 初始化角色树
	Page.ajaxPost("role/tree.do", null, function (response) {
		$(response.data).each(function(i, data) {
			data.chkDisabled = data.id.indexOf('dept-') == 0;
		});
		$scope.roleTree = $.fn.zTree.init($("#roleTree"), {
			check: {
				enable: true,
				chkStyle: 'checkbox', chkboxType: {'Y': '', 'N': '' }
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "parentId"
				},
				key: {
					name: "name"
				}
			},
			callback: {
				onCheck : function (event, treeId, treeNode) {
					var checkedNodes = $scope.roleTree.getCheckedNodes(true), nodes;
					$scope.$apply(function() {
						if (treeNode.checked) {// 选中，增加
							nodes = Ztree.difference(checkedNodes, $scope.roles, 'roleId');
							if (nodes.length != 1) {
								Page.notice('未知异常！');
								return;
							}
							Page.ajaxPut('userRole/' + $scope.user.userId + '/' + nodes[0].roleId + '.do', null, function() {
								$scope.roles = checkedNodes;
							});
						} else {// 减少
							nodes = Ztree.difference($scope.roles,checkedNodes,'roleId');
							if (nodes.length != 1) {
								Page.notice('未知异常！');
								return;
							}
							Page.ajaxDelete('userRole/' + $scope.user.userId + '/' + nodes[0].roleId + '.do', null, function() {
								$scope.roles = checkedNodes;
							});
						}
					});
				}
			}
		}, response.data);
	});

	// 添加用户角色
	$scope.addRole = function() {
		$scope.userRoleEdit = true;
		Ztree.unCheckAllNodes($scope.roleTree);
		Ztree.checkNodes($scope.roleTree, $scope.roles, 'roleId');

		// 展开
		$($scope.roles).each(function(i, role) {
			$scope.expandParent(role.deptId);
		});
	};
	$scope.expandParent = function(deptId) {
		var node = $scope.roleTree.getNodeByParam('deptId', deptId, null);
		if (node) {
			$scope.roleTree.expandNode(node, true);
			$scope.expandParent(node.parentId);
		}
	}

	// 删除用户角色
	$scope.delRole = function(roleId) {
		Page.confirm("确定要删除吗？", function () {
			Page.ajaxDelete('userRole/' + $scope.user.userId + '/' + roleId + '.do', null, function () {
				var roles = [];
				$($scope.roles).each(function(i, role) {
					if (role.roleId != roleId) {
						roles.push(role);
					}
				});
				$scope.roles = roles;
			});
		});
	};

	// 取消设置角色
	$scope.userRoleCancel = function() {
		$scope.userRoleEdit = false;
	};

	// 用户表格
    $scope.userGrid = {
		importFile : {},
		column_defs: [
			{
            	target: 1,
            	template: function(row){
            		return '<a href="javascript:void(0)" ed-click="open">'+row.userCode+'</a>';
            	}
            },
			{
				target: 6,
				buttons: [
					{
						name: '编辑',
						class: 'btn-edit',
						icon: 'fa-edit',
						event: 'update'
					},
					{
						name: '删除',
						class: 'btn-delete',
						icon: 'fa-trash-o',
						event: 'delete'
					},
					{
						name: '重置密码',
						class: 'btn-reset',
						icon: 'fa-cog',
						auth: 'resetPassword',
						event: 'resetPassword',
						visiable : function(row) {
                            return false;
                        }
					}
				]
			}
        ],
		resetPassword : function (row) {
			Page.ajaxPost('user/resetPassword.do', row, function() {
				$scope.userGrid.cancel();
				$scope.userGrid.query();
				Page.notice("密码重置成功！");
			});
		},
        update: function(row) {
            $scope.userGrid.edit = true;
            $scope.user = row;
        },
		save: function () {
			Page.ajaxPost($scope.user._add ? 'user/add.do' : 'user/update.do', $scope.user, function () {
				$scope.userGrid.cancel();
				$scope.userGrid.query({deptId: $scope.dept ? $scope.dept.deptId : ''});
				Page.notice('保存成功')
			});
		},
		delete : function(row){
			Page.confirm("确定要删除吗？", function () {
				Page.ajaxPost('user/delete.do', row, function () {
					$scope.userGrid.query({deptId: $scope.dept ? $scope.dept.deptId : ''});
				});
			});
		},
        open : function(row) {
			// 设置部门名称
			for (var i = 0; i < $scope.depts.length; i++) {
				if (row.deptId == $scope.depts[i].deptId) {
					row.deptName = $scope.depts[i].deptName;;
				}
			}
        	$scope.userInfo.show(event);

        	$scope.user = row;
			$scope.userRoleEdit = false;
			$scope.roles = null;

			Page.ajaxGet('userRole/' + row.userId + '.do',null, function(response) {
				$scope.roles = response.data;
			});
        },
		cancel : function() {
			$scope.userGrid.edit = false;
		},
		syncUsers : function(){
			Page.ajaxPost('sync/user/refresh.do', null, function(resp) {
        		Page.notice('用户数据刷新完成!');
        		$scope.userGrid.query();
    		});
		}
    };

	$scope.$watch("userGrid.importFile",function(newValue,oldValue,$scope){
		if(newValue && newValue.path != undefined){
			Page.ajaxPost('media/resource/importData.do', {path:$scope.userGrid.importFile.path}, function () {
				Page.notice('导入成功')
			});
		}
	})

}]);